<template>
	<view class="content">
		<view class="my_box">
			<view class="my_box_box">
				<picker mode="selector" :value="jiaIndex" :range="jiaList" range-key="text"
					@change="bindjiaListSelectChange">
					<view class="my_box_top">
						<view class="avatoa">
							<text class="my_txt required">申请类型</text>
						</view>
						<view class="icon_right">
							<text class="hint">{{getjiaListNmae(jiaIndex)}}</text>
							<view class="my_txt mytxt">
								<image class="arrow_icon" src="/static/images/me/to_right_icon.png" mode="scaleToFill">
								</image>
							</view>
						</view>
					</view>
				</picker>
				<picker v-if="showPractice" mode="selector" :value="processIndex" :range="practiceList" range-key="text"
					@change="bindpracticeSelectChange">
					<view class="my_box_top">
						<view class="avatoa">
							<text class="my_txt required">实习记录</text>
						</view>
						<view class="icon_right">
							<text class="hint">{{getProcessIdNmae(processIndex)}}</text>
							<view class="my_txt mytxt">
								<image class="arrow_icon" src="/static/images/me/to_right_icon.png" mode="scaleToFill">
								</image>
							</view>
						</view>
					</view>
				</picker>
			</view>
		</view>

		<view class="my_box">
			<view class="my_box_box">
				<!-- <picker :disabled="showPractice" mode="date" :value="startDateTime" :start="startDate" :end="endDate"
					@change="bindStartDateChange">
					<view class="my_box_top">
						<view class="avatoa">
							<text class="my_txt required">开始时间</text>
						</view>
						<view class="icon_right">
							<text class="hint">{{startDateTime}}</text>
							<view class="my_txt mytxt">
								<image class="arrow_icon" src="/static/images/me/to_right_icon.png" mode="scaleToFill">
								</image>
							</view>
						</view>
					</view>
				</picker>
				<picker :disabled="showPractice" mode="date" :value="endDateTime" :start="startDate" :end="endDate" @change="bindEndDateChange">
					<view class="my_box_top">
						<view class="avatoa">
							<text class="my_txt required">结束时间</text>
						</view>
						<view class="icon_right">
							<text class="hint">{{endDateTime}}</text>
							<view class="my_txt mytxt">
								<image class="arrow_icon" src="/static/images/me/to_right_icon.png" mode="scaleToFill">
								</image>
							</view>
						</view>
					</view>
				</picker> -->
				<uni-datetime-picker :disabled="showPractice" v-model="startDateTime" type="datetime" @change="bindStartDateChange">
					<view class="my_box_top">
						<view class="avatoa">
							<text class="my_txt required">开始时间</text>
						</view>
						<view class="icon_right">
							<text class="hint">{{startDateTime}}</text>
							<view class="my_txt mytxt">
								<image class="arrow_icon" src="/static/images/me/to_right_icon.png" mode="scaleToFill">
								</image>
							</view>
						</view>
					</view>
				</uni-datetime-picker>
				<uni-datetime-picker :disabled="showPractice" v-model="endDateTime" type="datetime" @change="bindEndDateChange">
					<view class="my_box_top">
						<view class="avatoa">
							<text class="my_txt required">结束时间</text>
						</view>
						<view class="icon_right">
							<text class="hint">{{endDateTime}}</text>
							<view class="my_txt mytxt">
								<image class="arrow_icon" src="/static/images/me/to_right_icon.png" mode="scaleToFill">
								</image>
							</view>
						</view>
					</view>
				</uni-datetime-picker>
				<view class="my_box_top">
					<view class="avatoa">
						<text class="my_txt required">天数</text>
					</view>
					<view class="icon_right">
						<!-- <input style="text-align: right; padding-right: 16rpx;" disabled="" type="text" v-model="jiaNum"
							placeholder="请输入天数" /> -->
							<view style="text-align: right; padding-right: 16rpx;">{{jiaNum?(jiaNum+'天（'+ askDayTxt +'）'):askDayTxt}}</view>
					</view>
				</view>
				<view class="my_box_top" v-if="jiaIndex != 11 && jiaIndex != 12">
					<view class="avatoa">
						<text class="my_txt">是否外出</text>
					</view>
					<view class="icon_right">
						<switch color="#185AFF" :checked='isLeaveOut' @change="leaveOutChange" />
					</view>
				</view>
			</view>
		</view>
		<view class="my_box">
			<view class="my_box_box">
				<view class="my_box_top"
					style="flex-direction: column;justify-content: flex-start;align-items: flex-start;">
					<view class="avatoa">
						<text class="my_txt required">事由</text>
					</view>
					<view class="icon_right" style="width: 100%;">
						<textarea v-model="leaveCause" style="margin-top: 20rpx;width: 100%;" placeholder="请输入此次申请事由" />
					</view>
				</view>
			</view>
		</view>
		<view class="btn_box">
			<button type="primary" class="btn_pri" @click="_toApply">提交申请</button>
		</view>

		<view class="hint" style="padding: 24rpx;">
			注：申请时间大于1个小时的记为半天；大于6小时的记为1天。
		</view>
		<mcModal :isShow="showMcModal" :content="content" :title="title" :showCancel="false" :inp="false" @ok='confirm()'
			:okBtn='okBtn'></mcModal>
	</view>
</template>

<script>
	import {
		applyLeave,
		getMyPracticeLeaveList,
		backLate
	} from '../../common/api/index.js';
	import {
		_showToast,
		dateFtt,
		mGetDate,
		_showLoading,
		datediff
	} from '../../common/js/util.js'
	import mcModal from '../../components/custom-modal/custom-modal.vue'
	export default {
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				startDateTime: currentDate + ' 00:00:00',
				endDateTime: currentDate + ' 23:59:59',
				jiaList: [],
				askTypes: [
				// 	{
				// 	text: '请选择',
				// 	value: '',
				// },
				{
					text: '事假',
					value: '1',
				}, {
					text: '病假',
					value: '2',
				}, {
					text: '年假',
					value: '3',
				}, {
					text: '婚假',
					value: '4',
				}, {
					text: '产检假',
					value: '5',
				}, {
					text: '产假',
					value: '6',
				}, {
					text: '陪产假',
					value: '7',
				}, {
					text: '丧假',
					value: '8',
				}, {
					text: '调休',
					value: '9',
				}, {
					text: '奖励假',
					value: '10',
				}, {
					text: '实习',
					value: '11',
				}, {
					text: '实习返校 ',
					value: '12',
				}, {
					text: '外出条 ',
					value: '13',
				}],
				jiaIndex: "0", // 选中请假的value
				jiaName: '', // 选中请假的值
				leaveCause: '', //事由
				applyType: 3,
				isLeaveOut: true,
				jiaNum: '',
				orgId: null,
				empId: null,
				showMcModal: false,
				content: '',
				title: '',
				okBtn: '',
				showPractice: false,
				processId: '',
				processIndex: 0,
				practiceName: '',
				practiceList: [],
				askDayTxt: '1天',
				backLateTime: null
			}
		},
		onLoad(option) {
			this.orgId = option.orgId
			this.empId = option.empId
			this.applyType = option.applyType
			this._calculate()
			this._getMyPracticeLeaveList()
			this.check(this.askTypes, this.applyType)
		},
		components: {
			mcModal
		},
		methods: {
			check(data, type) {
				let newData = data.filter(item => {
					if(type == 1) {
						return item.value == '13'
					}else if(type == 2) {
						return item.value == '11' || item.value == '12'
					}else if(type == 3) {
						return parseInt(item.value) < 11
					}else {
						return true
					}
				})
				this.jiaList = (type == 1 || type == 2 ? [] : [{text: '请选择', value: ''}]).concat(newData)
				type == 2 ? this.bindjiaListSelectChange({target:{value: '0'}}) : this.showPractice = false
				if(type == 1) this._backLate()
			},
			confirm(){
				this.showMcModal = false
			},
			bb() {
				this.showMcModal = false
			},
			cc() {
				this.showMcModal = false
				uni.navigateBack({
					delta: 1
				})
			},
			bindjiaListSelectChange(e) {
				let index = e.target.value
				this.jiaIndex = index
				if(this.jiaList[index].value == 12 || this.jiaList[index].value == 11) this.isLeaveOut = true
				
				if (this.jiaList[index].value == 12) {
					this.showPractice = true
					this._getMyPracticeLeaveList()
				} else {
					this.showPractice = false
				}
			},
			bindpracticeSelectChange(e) {
				this.processIndex = e.target.value
				this.processId = this.practiceList[e.target.value].value
				this.startDateTime = this.practiceList[e.target.value].date[0]
				this.endDateTime = this.practiceList[e.target.value].date[1]
				this._calculate()

			},
			bindStartDateChange: function(e) {
				this.startDateTime = e.slice(0, this.startDateTime.length - 2) + '00'
				this._calculate('start')
			},
			bindEndDateChange: function(e) {
				this.endDateTime = e.slice(0, this.startDateTime.length - 2) + '00'
				this._calculate('end')
			},
			leaveOutChange(e) {
				console.log(e)
				this.isLeaveOut = e.target.value
			},
			_getMyPracticeLeaveList() {
				this.practiceList = [{
					text: '请选择',
					value: ''
				}]
				getMyPracticeLeaveList({
					orgId: this.orgId,
					empId: this.empId,
				}).then(res => {
					if (res.resultCode == 0) {
						if (!res.leaveList) return
						res.leaveList.forEach(item => {
							this.practiceList.push({
								date: [item.leaveStartTime, item.leaveEndTime],
								text: dateFtt('yyyy-MM-dd', item.leaveStartTime) + '至' + dateFtt(
									'yyyy-MM-dd', item.leaveEndTime),
								value: item.processId
							})
						})
					} else {
						_showToast(res.resultMsg)
					}
					console.log(this.practiceList)
				})
			},
			_toApply() {
				if (this.jiaList[this.jiaIndex].value == '') {
					_showToast("请选择申请类型")
					return
				}
				if(!this._calculate()){
					return
				}
				// if (new Date(this.endDateTime.replace(/-/g, "/")).getTime() - new Date(this.startDateTime.replace(/-/g,
				// 		"/")).getTime() <= 0) {
				// 	_showToast("结束时间不小于等于开始时间")
				// 	return
				// }
				// if (this.jiaNum < 0.5) {
				// 	_showToast('请假起止时间段太短，不支持发起');
				// 	return
				// }
				if (this.leaveCause == '') {
					_showToast("请填写申请事由")
					return
				}
				if (this.showPractice && this.processId == '') {
					_showToast("请选择对应实习申请记录")
					return
				}
				_showLoading('提交中...')
				let data = {
					orgId: this.orgId,
					empId: this.empId,
					leaveType: this.jiaList[this.jiaIndex].value,
					drLeave: {
						fillTime: "",
						empId: this.empId,
						leaveType: this.jiaList[this.jiaIndex].value,
						leaveStartTime: this.startDateTime,
						leaveEndTime: this.endDateTime,
						leaveDay: this.jiaNum,
						leaveCause: this.leaveCause,
						isLeaveOut: +this.isLeaveOut,
						parentId: this.processId
					}
				}
				if (!this.showPractice) delete data.drLeave.parentId // data.drLeave.parentId = this.processId

				applyLeave(data).then(res => {
					uni.hideLoading()
					if (res.resultCode === 0) {
						this.title = '温馨提示'
						this.content = '申请提交成功，请耐心等待审核~'
						this.okBtn = '确认'
						this.showMcModal = true
						this.confirm = this.cc
					} else {
						this.title = '提示'
						this.content = res.resultMsg,
						this.okBtn = '确认'
						this.showMcModal = true
						this.confirm = this.bb
					}
				})
			},
			_calculate(type) {
				// 赋值前判断
				let diff = datediff(this.startDateTime.replace(/-/g, "/"), this.endDateTime.replace(/-/g, "/"))
				if (diff <= 0) {
					uni.showToast({
						title: '结束时间不小于等于开始时间',
						duration: 2000,
						icon: 'none'
					});
					return false
				}
				if(this.applyType == 1 && this.backLateTime) {
					let backLateDiff = datediff(this.endDateTime.replace(/-/g, "/"), dateFtt('yyyy-MM-dd', this.endDateTime).replace(/-/g, "/") + ' ' + this.backLateTime.startTime)
					if(backLateDiff < 0){
						uni.showToast({
							title: '结束时间不能超过晚归时间',
							duration: 2000,
							icon: 'none'
						});
						this.$nextTick(() => {
							this.endDateTime = dateFtt('yyyy-MM-dd', this.endDateTime) + ' ' + this.backLateTime.startTime;
							this._calculate()
						})
						return false
					}
				}
				
				// 赋值后判断
				this.jiaNum = diff % 1 * 24 < 1 && diff < 1 ? 0.1 : (diff % 1 * 24 >= 6 ? (Number.parseInt(diff) + 1) : (Number.parseInt(
					diff) + (diff % 1 * 24 == 0 ? 0 : 0.5)))
				if (diff > 1) {
					if(this.applyType == 1) {
						uni.showToast({
							title: '开始时间和结束时间只能同一天',
							duration: 2000,
							icon: 'none'
						});
						this.$nextTick(() => {
							if(type == 'start') this.endDateTime = dateFtt('yyyy-MM-dd', this.startDateTime) + ' 23:59:59';
							else this.startDateTime = dateFtt('yyyy-MM-dd', this.endDateTime) + ' 00:00:00';
							this._calculate()
						})
						return false
					}
					this.askDayTxt = Number.parseFloat(diff).toFixed(2) + "天"
					return true
				}
				diff = diff * 24
				if (diff > 1) {
					this.askDayTxt = Number.parseFloat(diff).toFixed(2) + "小时"
					return true
				}
				diff = diff * 60
				if (diff > 1) {
					this.askDayTxt = Number.parseFloat(diff).toFixed(2) + "分钟"
					return true
				}
			},
			_backLate(){
				backLate({orgId: this.orgId}).then(res => {
					if(res.resultCode == 0){
						// this.backLateTime = res.data.length > 0 ? res.data[0] : {endTime: this.endDateTime, startTime: this.startDateTime}
						this.backLateTime = res.data.length > 0 ? res.data[0] : null
					}else {
						uni.showToast({
							title: '晚归时间获取失败：' + res.resultMsg,
							duration: 2000,
							icon: 'none'
						});
					}
				})
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			}
		},
		computed: {
			getjiaListNmae(index) {
				return function(index) {
					return this.jiaList[index].text
				}
			},
			getProcessIdNmae(index) {
				return function(index) {
					return this.practiceList[index].text
				}
			},
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		}
	}
</script>

<style lang="scss">
	page {
		height: 100vh;
		background-color: #f6f6f6;
		font-family: PingFang-SC-Heavy, PingFang-SC;
	}

	.content {
		height: 100%;
		box-sizing: border-box;
		overflow-y: auto;
	}

	.my_box {
		margin-top: 16rpx;
	}

	.my_box_box {
		display: flex;
		flex-direction: column;
	}

	.my_box_top {
		min-height: 106rpx;
		padding: 24rpx 32rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		background-color: #FFFFFF;
		position: relative;

		&::after {
			content: "";
			height: 1px;
			transform: scaleY(.5);
			background: #E6E6E6;
			position: absolute;
			right: 0;
			bottom: 0;
			left: 32rpx;
		}

		&:last-child::after {
			height: 0;
		}
	}

	.avatoa {
		display: flex;
		align-items: center;
	}

	.imgava {
		width: 48rpx;
		height: 48rpx;
		margin-right: 15rpx;
	}

	.my_txt {
		font-family: PingFangSC;
		font-weight: 800;
		font-size: 30rpx;
		color: #3C424F;
	}

	.required::before {
		content: "* ";
		font-weight: 800;
		color: #FA6400;
	}

	.mytxt {
		color: rgb(199, 199, 204);
		line-height: 0;
	}

	.arrow_icon {
		display: inline-block;
		width: 48rpx;
		height: 48rpx;
	}

	.icon_right {
		display: flex;
		flex-direction: row;
		align-items: center;

		input {
			width: 160rpx;
		}
	}

	.hint {
		font-size: 30rpx;
		font-weight: 500;
		color: #ADADAD;
		line-height: 42rpx;
		margin-right: 26rpx;
	}

	.btn_pri {
		width: 566rpx;
		height: 96rpx;
		line-height: 96rpx;
		font-weight: 800;
		background: linear-gradient(90deg, #0685FF 0%, #285EFF 100%);
		box-shadow: 0 16rpx 32rpx 0 rgba(36, 98, 255, 0.24);
		border-radius: 9rpx;
		margin: 60rpx auto 30rpx;
	}
</style>
